package edu.sdjzu.exam.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import edu.sdjzu.exam.common.CommonResponse;
import edu.sdjzu.exam.domain.exam.ExamAnswer;
import edu.sdjzu.exam.dto.ExamAnswerSubmitDTO;
import edu.sdjzu.exam.service.exam.ExamAnswerService;
import edu.sdjzu.exam.service.exam.AutoGradingService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/exam-answers")
@RequiredArgsConstructor
@SaCheckLogin
public class ExamAnswerController {

    private final ExamAnswerService examAnswerService;

    /**
     * 学生提交考试答案（触发自动判卷）
     */
    @PostMapping("/submit")
    @SaCheckRole("student")
    public CommonResponse<?> submitExamAnswers(
            @Valid @RequestBody ExamAnswerSubmitDTO submitDTO) {
        try {
            AutoGradingService.AutoGradingResult result = examAnswerService.submitExamAnswers(submitDTO);
            return CommonResponse.success("考试答案提交成功，自动判卷完成", result);
        } catch (Exception e) {
            return CommonResponse.error("提交失败：" + e.getMessage());
        }
    }


    /**
     * 保存答案草稿
     */
    @PostMapping("/draft")
    @SaCheckRole("student")
    public CommonResponse<String> saveAnswerDraft(@Valid @RequestBody ExamAnswerSubmitDTO submitDTO) {
        try {
            examAnswerService.saveAnswerDraft(submitDTO);
            return CommonResponse.success("草稿保存成功");
        } catch (Exception e) {
            return CommonResponse.error("保存失败：" + e.getMessage());
        }
    }

    /**
     * 获取学生的考试答案（学生查看自己的答案）
     */
    @GetMapping("/my/{examId}")
    @SaCheckRole("student")
    public CommonResponse<List<ExamAnswer>> getMyAnswers(@PathVariable Long examId) {
        try {
            List<ExamAnswer> answers = examAnswerService.getStudentAnswers(examId, null);
            return CommonResponse.success(answers);
        } catch (Exception e) {
            return CommonResponse.error("获取失败：" + e.getMessage());
        }
    }

    /**
     * 教师查看指定学生的考试答案
     */
    @GetMapping("/student/{examId}/{studentId}")
    @SaCheckRole("teacher")
    public CommonResponse<List<ExamAnswer>> getStudentAnswers(
            @PathVariable Long examId, 
            @PathVariable Long studentId) {
        try {
            List<ExamAnswer> answers = examAnswerService.getStudentAnswers(examId, studentId);
            return CommonResponse.success(answers);
        } catch (Exception e) {
            return CommonResponse.error("获取失败：" + e.getMessage());
        }
    }
} 